import { createStore } from 'vuex'

// Vuex 中的数据保存在运行内存中，刷新页面会消失，所以需要从缓存中拿初始值
const userInfo = uni.getStorageSync('userInfo')
const systemSet = uni.getStorageSync('systemSet')
const openSerial = uni.getStorageSync('openSerial')
const openBatch = uni.getStorageSync('openBatch')

const store = createStore({
  state: {
    // 用户信息
    userInfo: userInfo || null,
    // 系统设置
    systemSet: systemSet || [],
    // 序列号
    openSerial: openSerial || false,
    // 批次
    openBatch: openBatch || false,
  },
  mutations: {
    // 设置用户信息
    setUserInfo(state, param) {
      state.userInfo = param
    },
    // 设置系统设置
    setSystemSet(state, param) {
      state.systemSet = param
    },
    // 设置序列号
    setOpenSerial(state, param) {
      state.openSerial = param
    },
    // 设置批次
    setOpenBatch(state, param) {
      state.openBatch = param
    }
  },
  getters: {
    // 根据名称获取系统设置
    getSystemSetByName: (state) => (name) => {
      const findRes = state.systemSet.find(item => item.name === name)
      if (findRes) {
        if (findRes.id >= 11 && findRes.id <= 25) {
          return findRes.is_checked == 1
        } else {
          return findRes.value
        }
      }
    }
  }
})

export default store
